<template>
  <view class="order-detail-container">
    <!-- 顶部导航 -->
    <view class="header">
      <view class="back-btn" @click="goBack">
        <text class="iconfont icon-back">←</text>
      </view>
      <view class="title">订单详情</view>
      <view class="more-btn"></view>
    </view>
    
    <!-- 订单状态 -->
    <view class="status-section" :class="statusClass">
      <view class="status-icon">
        <text v-if="order.status === 'paid'">✓</text>
        <text v-else-if="order.status === 'pending'">!</text>
        <text v-else>×</text>
      </view>
      <view class="status-text">{{ getStatusText(order.status) }}</view>
      <view class="status-desc" v-if="order.status === 'paid'">
        凭借电子票或订单号到景区换取门票
      </view>
      <view class="status-desc" v-else-if="order.status === 'pending'">
        请在30分钟内完成支付，超时订单将自动取消
      </view>
      <view class="status-desc" v-else>
        订单已取消，可重新预订
      </view>
    </view>
    
    <!-- 景点信息 -->
    <view class="card-section">
      <view class="card-title">景点信息</view>
      <view class="card-content">
        <image :src="getScenicImage(order.scenicId)" mode="aspectFill" class="scenic-image"></image>
        <view class="scenic-info">
          <view class="scenic-name">{{ order.scenicName }}</view>
          <view class="ticket-name">{{ order.ticketName }} x {{ order.quantity }}</view>
          <view class="visit-date">游览日期: {{ formatDate(order.visitDate) }}</view>
        </view>
      </view>
    </view>
    
    <!-- 订单信息 -->
    <view class="card-section">
      <view class="card-title">订单信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">订单号</text>
          <text class="info-value">{{ order.id }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">下单时间</text>
          <text class="info-value">{{ formatTime(order.createTime) }}</text>
        </view>
        <view class="info-item" v-if="order.status === 'paid'">
          <text class="info-label">支付时间</text>
          <text class="info-value">{{ formatTime(order.payTime) }}</text>
        </view>
        <view class="info-item" v-if="order.status === 'cancelled'">
          <text class="info-label">取消时间</text>
          <text class="info-value">{{ formatTime(order.cancelTime) }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">支付方式</text>
          <text class="info-value">{{ getPaymentMethodText(order.paymentMethod) }}</text>
        </view>
      </view>
    </view>
    
    <!-- 联系人信息 -->
    <view class="card-section">
      <view class="card-title">联系人信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">联系人</text>
          <text class="info-value">{{ order.contactName }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">手机号</text>
          <text class="info-value">{{ order.contactPhone }}</text>
        </view>
      </view>
    </view>
    
    <!-- 金额信息 -->
    <view class="card-section">
      <view class="card-title">金额信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">门票单价</text>
          <text class="info-value">¥{{ order.price }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">数量</text>
          <text class="info-value">{{ order.quantity }}张</text>
        </view>
        <view class="info-item total">
          <text class="info-label">总计</text>
          <view class="price">
            <text class="price-symbol">¥</text>
            <text class="price-value">{{ order.totalAmount }}</text>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 电子票二维码 -->
    <view class="card-section" v-if="order.status === 'paid'">
      <view class="card-title">电子票凭证</view>
      <view class="ticket-qrcode">
        <view class="qrcode-container">
          <image src="http://114.55.56.174:19000/shzy/临时票.png" mode="aspectFit" style="width: 200px; height: 200px;"></image>
        </view>
        <view class="qrcode-tip">请向检票人员出示此凭证</view>
      </view>
    </view>
    
    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <view class="action-btn cancel" @tap="cancelOrder" v-if="order.status === 'pending' || order.status === 'paid'">
        取消订单
      </view>
      <view class="action-btn print" @tap="printTicket" v-if="order.status === 'paid'">
        打印票据
      </view>
      <view class="action-btn pay primary" @tap="payOrder" v-if="order.status === 'pending'">
        去支付
      </view>
    </view>
  </view>
</template>

<script>
import { checkNeedLogin, getUserInfo } from '../../../utils/auth.js';

export default {
  data() {
    return {
      orderId: '',
      order: {
        id: '',
        scenicId: 0,
        scenicName: '',
        ticketId: 0,
        ticketName: '',
        price: 0,
        quantity: 0,
        totalAmount: 0,
        visitDate: '',
        contactName: '',
        contactPhone: '',
        createTime: '',
        status: 'pending',
        paymentMethod: '',
        payTime: '',
        cancelTime: ''
      },
      userInfo: null,
      scenicImages: {
        // 缓存景点图片
        1: 'http://114.55.56.174:19000/shzy/故宫.jpg',
        2: 'http://114.55.56.174:19000/shzy/八达岭长城.jpg',
        3: 'http://114.55.56.174:19000/shzy/颐和园.png',
        4: 'http://114.55.56.174:19000/shzy/大唐不夜城.png',
        5: 'http://114.55.56.174:19000/shzy/天坛公园.png',
        6: 'http://114.55.56.174:19000/shzy/鸟巢.png'
      }
    }
  },
  onLoad(option) {
    if (checkNeedLogin()) return;
    
    // 获取订单ID
    this.orderId = option.orderId || '';
    if (!this.orderId) {
      uni.showToast({
        title: '订单ID无效',
        icon: 'none'
      });
      setTimeout(() => {
        uni.navigateBack();
      }, 1500);
      return;
    }
    
    // 获取用户信息
    this.getUserData();
    
    // 加载订单详情
    this.loadOrderDetail();
  },
  methods: {
    // 获取用户信息
    getUserData() {
      this.userInfo = getUserInfo();
    },
    
    // 加载订单详情
    loadOrderDetail() {
      try {
        // 从本地存储获取所有订单
        const allOrders = uni.getStorageSync('userOrders') || [];
        
        // 查找当前订单
        const currentOrder = allOrders.find(o => o.id === this.orderId);
        
        if (currentOrder) {
          // 检查订单是否属于当前用户
          if (this.userInfo && this.userInfo.userId && 
              currentOrder.userId && currentOrder.userId !== this.userInfo.userId) {
            uni.showToast({
              title: '无权查看此订单',
              icon: 'none'
            });
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
            return;
          }
          
          this.order = currentOrder;
          console.log('加载订单详情成功:', this.order);
        } else {
          uni.showToast({
            title: '订单不存在',
            icon: 'none'
          });
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        }
      } catch (error) {
        console.error('加载订单详情失败:', error);
        uni.showToast({
          title: '加载订单失败',
          icon: 'none'
        });
      }
    },
    
    // 获取订单状态文本
    getStatusText(status) {
      switch (status) {
        case 'pending': return '等待支付';
        case 'paid': return '支付成功';
        case 'cancelled': return '订单已取消';
        default: return '未知状态';
      }
    },
    
    // 获取订单状态类名
    getStatusClass(status) {
      switch (status) {
        case 'pending': return 'status-pending';
        case 'paid': return 'status-paid';
        case 'cancelled': return 'status-cancelled';
        default: return '';
      }
    },
    
    // 获取支付方式文本
    getPaymentMethodText(method) {
      switch (method) {
        case 'wechat': return '微信支付';
        case 'alipay': return '支付宝';
        default: return '其他支付方式';
      }
    },
    
    // 格式化日期
    formatDate(dateString) {
      if (!dateString) return '';
      const date = new Date(dateString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')}`;
    },
    
    // 格式化时间
    formatTime(timeString) {
      if (!timeString) return '';
      const date = new Date(timeString);
      return `${date.getFullYear()}-${(date.getMonth() + 1).toString().padStart(2, '0')}-${date.getDate().toString().padStart(2, '0')} ${date.getHours().toString().padStart(2, '0')}:${date.getMinutes().toString().padStart(2, '0')}`;
    },
    
    // 获取景点图片
    getScenicImage(scenicId) {
      return this.scenicImages[scenicId] || '/static/images/default-scenic.jpg';
    },
    
    // 取消订单
    cancelOrder() {
      uni.showModal({
        title: '取消订单',
        content: '确定要取消该订单吗？',
        success: (res) => {
          if (res.confirm) {
            // 获取所有订单
            const allOrders = uni.getStorageSync('userOrders') || [];
            
            // 找到当前订单的索引
            const orderIndex = allOrders.findIndex(o => o.id === this.orderId);
            
            if (orderIndex !== -1) {
              // 更新订单状态为已取消
              allOrders[orderIndex].status = 'cancelled';
              allOrders[orderIndex].cancelTime = new Date().toISOString();
              
              // 保存更新后的订单
              uni.setStorageSync('userOrders', allOrders);
              
              // 更新当前显示的订单
              this.order = allOrders[orderIndex];
              
              uni.showToast({
                title: '订单已取消',
                icon: 'success'
              });
            }
          }
        }
      });
    },
    
    // 打印票据
    printTicket() {
      uni.showToast({
        title: '正在生成票据...',
        icon: 'loading',
        duration: 1500
      });
      
      setTimeout(() => {
        uni.navigateTo({
          url: `/pages/user/orders/ticket?orderId=${this.orderId}`
        });
      }, 1500);
    },
    
    // 支付订单
    payOrder() {
      uni.showLoading({
        title: '正在处理...'
      });
      
      setTimeout(() => {
        // 显示支付选择
        uni.hideLoading();
        
        uni.showActionSheet({
          itemList: ['微信支付', '支付宝'],
          success: (res) => {
            const paymentMethod = res.tapIndex === 0 ? 'wechat' : 'alipay';
            
            uni.showLoading({
              title: '支付处理中...'
            });
            
            // 模拟支付过程
            setTimeout(() => {
              // 获取所有订单
              const allOrders = uni.getStorageSync('userOrders') || [];
              
              // 找到当前订单的索引
              const orderIndex = allOrders.findIndex(o => o.id === this.orderId);
              
              if (orderIndex !== -1) {
                // 更新订单状态为已支付
                allOrders[orderIndex].status = 'paid';
                allOrders[orderIndex].payTime = new Date().toISOString();
                allOrders[orderIndex].paymentMethod = paymentMethod;
                
                // 保存更新后的订单
                uni.setStorageSync('userOrders', allOrders);
                
                // 更新当前显示的订单
                this.order = allOrders[orderIndex];
                
                uni.hideLoading();
                uni.showToast({
                  title: '支付成功',
                  icon: 'success'
                });
              } else {
                uni.hideLoading();
                uni.showToast({
                  title: '订单处理失败',
                  icon: 'none'
                });
              }
            }, 2000);
          }
        });
      }, 1000);
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack();
    }
  },
  computed: {
    statusClass() {
      return this.getStatusClass(this.order.status);
    }
  }
}
</script>

<style lang="scss">
.order-detail-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 140rpx;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20rpx 30rpx;
  background: #fff;
  position: sticky;
  top: 0;
  z-index: 100;
  
  .back-btn, .more-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    
    .iconfont {
      font-size: 40rpx;
      color: #333;
    }
  }
  
  .title {
    flex: 1;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.status-section {
  padding: 40rpx 30rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  
  &.status-pending {
    background: linear-gradient(135deg, #ffa500, #ff8c00);
    
    .status-icon {
      background: rgba(255, 255, 255, 0.2);
    }
  }
  
  &.status-paid {
    background: linear-gradient(135deg, #4080ff, #1a56ff);
    
    .status-icon {
      background: rgba(255, 255, 255, 0.2);
    }
  }
  
  &.status-cancelled {
    background: linear-gradient(135deg, #999, #666);
    
    .status-icon {
      background: rgba(255, 255, 255, 0.2);
    }
  }
  
  .status-icon {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-bottom: 20rpx;
    
    text {
      font-size: 40rpx;
      font-weight: bold;
      color: #fff;
    }
  }
  
  .status-text {
    font-size: 36rpx;
    font-weight: bold;
    color: #fff;
    margin-bottom: 16rpx;
  }
  
  .status-desc {
    font-size: 26rpx;
    color: rgba(255, 255, 255, 0.8);
    text-align: center;
  }
}

.card-section {
  margin: 20rpx 30rpx;
  background: #fff;
  border-radius: 12rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
  
  .card-title {
    font-size: 30rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 20rpx;
    position: relative;
    padding-left: 20rpx;
    
    &:before {
      content: '';
      position: absolute;
      left: 0;
      top: 6rpx;
      width: 8rpx;
      height: 30rpx;
      background: #4080ff;
      border-radius: 4rpx;
    }
  }
  
  .card-content {
    display: flex;
    
    .scenic-image {
      width: 180rpx;
      height: 120rpx;
      border-radius: 8rpx;
      margin-right: 20rpx;
    }
    
    .scenic-info {
      flex: 1;
      
      .scenic-name {
        font-size: 30rpx;
        font-weight: bold;
        color: #333;
        margin-bottom: 10rpx;
      }
      
      .ticket-name {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 10rpx;
      }
      
      .visit-date {
        font-size: 24rpx;
        color: #999;
      }
    }
  }
  
  .info-list {
    .info-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 16rpx 0;
      
      .info-label {
        font-size: 28rpx;
        color: #666;
      }
      
      .info-value {
        font-size: 28rpx;
        color: #333;
      }
      
      &.total {
        margin-top: 16rpx;
        border-top: 1rpx dashed #eee;
        padding-top: 30rpx;
        
        .info-label {
          font-size: 32rpx;
          font-weight: bold;
          color: #333;
        }
        
        .price {
          display: flex;
          align-items: baseline;
          
          .price-symbol {
            font-size: 24rpx;
            color: #ff4d4f;
          }
          
          .price-value {
            font-size: 36rpx;
            font-weight: bold;
            color: #ff4d4f;
          }
        }
      }
    }
  }
  
  .ticket-qrcode {
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 20rpx 0;
    
    .qrcode-container {
      margin: 20rpx auto;
      text-align: center;
      background: #fff;
      padding: 20rpx;
      border-radius: 8rpx;
      box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);
    }
    
    .qrcode-tip {
      font-size: 26rpx;
      color: #666;
    }
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 100rpx;
  background: #fff;
  display: flex;
  align-items: center;
  justify-content: flex-end;
  padding: 0 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  
  .action-btn {
    height: 70rpx;
    padding: 0 30rpx;
    border-radius: 35rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-left: 20rpx;
    font-size: 28rpx;
    
    &.cancel {
      border: 1rpx solid #ddd;
      color: #666;
    }
    
    &.print {
      background: #f0f8ff;
      color: #4080ff;
      border: 1rpx solid #d6e6ff;
    }
    
    &.primary {
      background: #4080ff;
      color: #fff;
    }
  }
}
</style> 